﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
using System.Linq;
using ToolBoxPro;
using LinqObj;

public partial class propertylist : RedirectPage
{
    private int propertyID;
    public int PropertyID { get { return this.propertyID; } set { this.propertyID = value; } }
    
    ToolboxDataContext tdc = new ToolboxDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        // To prevent the browser to cache the page.
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.MinValue);

        if (Request.QueryString["msg"] != null && Request.QueryString["msg"].ToString().Trim() != "")
        {
            if(Request.QueryString["msg"].ToString().Trim() == "add")
                lblmsg.Text = "Property has been added successfully.";
            else if (Request.QueryString["msg"].ToString().Trim() == "edit")
                lblmsg.Text = "Property has been edited successfully.";
            else if (Request.QueryString["msg"].ToString().Trim() == "ordersent")
                lblmsg.Text = "Order sent successfully.";
        }

        if (!IsPostBack)
        {
            ((Label)Master.FindControl("lblTitle")).Text = "Manage Property";
            ((System.Web.UI.HtmlControls.HtmlImage)Master.FindControl("imgHeading")).Src = "images/icon_manage.gif";

            //IEnumerable<Property> propertyList = Property.LoadPropertyList(Int32.Parse(Session[FormContract.AGENT_GROUP_ID].ToString()));
            //PropertyListBuilder propertyListGenerator = new PropertyListBuilder(propertyList);
            //this.propertyList.Controls.Add(propertyListGenerator.BuildPropertyList());
            FillGrid();           
        }
    }

    private void FillGrid()
    {
        var data = from _property in tdc.GetTable<Property>()
                   where _property.agent_group_id == Int32.Parse(Session[FormContract.AGENT_GROUP_ID].ToString())
                   select _property;

        if (this.ViewState["SortExpression"] != null)
        {
            string sortorder = ViewState["SortOrder"].ToString();

            if (sortorder == "DESC")
            {
                if (ViewState["SortExpression"].ToString() == "property_id")
                    data = data.OrderByDescending(a => a.property_id);
                else if (ViewState["SortExpression"].ToString() == "created_date")
                    data = data.OrderByDescending(a => a.created_date);
                else if (ViewState["SortExpression"].ToString() == "last_modified_date")
                    data = data.OrderByDescending(a => a.last_modified_date);

                gvpropertylist.DataSource = data;
                gvpropertylist.DataBind();
            }
            else if (sortorder == "ASC")
            {
                if (ViewState["SortExpression"].ToString() == "property_id")
                    data = data.OrderBy(a => a.property_id);
                else if (ViewState["SortExpression"].ToString() == "created_date")
                    data = data.OrderBy(a => a.created_date);
                else if (ViewState["SortExpression"].ToString() == "last_modified_date")
                    data = data.OrderBy(a => a.last_modified_date);

                gvpropertylist.DataSource = data;
                gvpropertylist.DataBind();
            }
        }
        else
        {
            gvpropertylist.DataSource = data.OrderByDescending(a => a.property_id);
            gvpropertylist.DataBind();
        }
    }

    protected void gvpropertylist_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvpropertylist.PageIndex = e.NewPageIndex;
        FillGrid();
    }

    protected void gvpropertylist_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label createdate = (Label)e.Row.FindControl("createdate");
            Label modifieddate = (Label)e.Row.FindControl("modifieddate");
            Label vStatus = (Label)e.Row.FindControl("vStatus");
            
            Label statuslabel = (Label)e.Row.FindControl("statusLabel");
            HtmlTableCell container = (HtmlTableCell)e.Row.FindControl("imagediv");

            if (DataBinder.Eval(e.Row.DataItem, "propertystatuslabel") != null)
            {
                string str1 = DataBinder.Eval(e.Row.DataItem, "propertystatuslabel").ToString();

                if(str1.Trim().ToUpper() == "ACTIVE")
                    statuslabel.Text = "<span class='activebf'>" + str1 + "</span>";
                else if(str1.Trim().ToUpper() == "INACTIVE")
                    statuslabel.Text = "<span class='inactive'>" + str1 + "</span>";
            }

            if (DataBinder.Eval(e.Row.DataItem, "allocated_status") != null)
            {
                var getAllocatedStatus = (from a in tdc.GetTable<Allocated_Status>()
                                          where a.status_id == Int32.Parse(DataBinder.Eval(e.Row.DataItem, "allocated_status").ToString())
                                          select a).Single();

                var Campaign = (from c in tdc.Campaigns
                                where c.property_id == Int32.Parse(DataBinder.Eval(e.Row.DataItem, "property_id").ToString())
                                select c).Single();

                HtmlGenericControl p = new HtmlGenericControl("div");
                container.Controls.Add(p);

                HtmlGenericControl shoppingCarThumbNail = new HtmlGenericControl("div");
                shoppingCarThumbNail.Attributes["class"] = getAllocatedStatus.status;
                shoppingCarThumbNail.Attributes["style"] = "color:#242527;";
                if(getAllocatedStatus.status.ToString().Equals("ordered"))
                    shoppingCarThumbNail.Attributes["id"] = Campaign.campaign_id.ToString();
                else
                    shoppingCarThumbNail.Attributes["id"] = DataBinder.Eval(e.Row.DataItem, "property_id").ToString();
                    
                shoppingCarThumbNail.InnerText = ".";
                p.Controls.Add(shoppingCarThumbNail);
            }

            string str;

            if (DataBinder.Eval(e.Row.DataItem, "vendor_status") != null)
            {
                str = DataBinder.Eval(e.Row.DataItem, "vendor_status").ToString();

                if (str.Trim() != "")
                {
                    var _lookups = (from _vendor_status in tdc.GetTable<Vendor_Status>()
                                    where _vendor_status.vendor_status_id == Int32.Parse(str)
                                    select _vendor_status).Single();
                    
                    vStatus.Text = _lookups.vendor_status1;
                }
            }

            if (DataBinder.Eval(e.Row.DataItem, "created_date") != null)
            {
                createdate.Text = FormContract.GetDateLabel(DateTime.Parse(DataBinder.Eval(e.Row.DataItem, "created_date").ToString()));
            }

            if (DataBinder.Eval(e.Row.DataItem, "last_modified_date") != null)
            {
                modifieddate.Text = FormContract.GetDateLabel(DateTime.Parse(DataBinder.Eval(e.Row.DataItem, "last_modified_date").ToString()));
            }
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label count = (Label)e.Row.FindControl("footercount");
            Label Label1 = (Label)e.Row.FindControl("Label1");
            Label Label2 = (Label)e.Row.FindControl("Label2");
            DropDownList ddlPage = (DropDownList)e.Row.FindControl("ddlPage");

            SortedList<string, string> pageHashing = new SortedList<string, string>();

            count.Text = "Total Records: " + (1 + (((GridView)sender).PageIndex * ((GridView)sender).PageSize)) + " - " + (((GridView)sender).Rows.Count + (((GridView)sender).PageIndex * ((GridView)sender).PageSize));
            Label2.Text = "Page: " + (((GridView)sender).PageIndex + 1) + " of " + ((GridView)sender).PageCount;

            ddlPage.Items.Insert(0, new ListItem("10", "10"));
            ddlPage.Items.Insert(1, new ListItem("15", "15"));
            ddlPage.Items.Insert(2, new ListItem("25", "25"));
            ddlPage.Items.Insert(3, new ListItem("50", "50"));
            ddlPage.Items.Insert(4, new ListItem("100", "100"));

            if (ViewState["objPageValue"] != null && ViewState["objPageValue"].ToString() != "0")
            {
                ddlPage.Items.FindByValue(ViewState["objPageValue"].ToString()).Selected = true;
            }
        }
    }

    protected void ddlPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList tempddlPage = (DropDownList)sender;
        ViewState["objPageValue"] = tempddlPage.SelectedValue;
        gvpropertylist.PageSize = Int32.Parse(tempddlPage.SelectedValue);
        FillGrid();
    }

    protected void gvpropertylist_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Sort"))
        {
            if (ViewState["SortExpression"] != null)
            {
                if (this.ViewState["SortExpression"].ToString() == e.CommandArgument.ToString())
                {
                    if (ViewState["SortOrder"].ToString() == "ASC")
                    {
                        ViewState["SortOrder"] = "DESC";
                    }
                    else
                    {
                        ViewState["SortOrder"] = "ASC";
                    }
                }
                else
                {
                    ViewState["SortOrder"] = "DESC";
                    ViewState["SortExpression"] = e.CommandArgument.ToString();
                }
            }
            else
            {
                ViewState["SortExpression"] = e.CommandArgument.ToString();
                ViewState["SortOrder"] = "ASC";
            }

            FillGrid();
        }
    }

    protected void gvpropertylist_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            ImageButton img1 = (ImageButton)e.Row.FindControl("ImageButton1");
            ImageButton img2 = (ImageButton)e.Row.FindControl("ImageButton2");
            ImageButton img3 = (ImageButton)e.Row.FindControl("ImageButton3");

            if (ViewState["SortExpression"] != null)
            {
                string sortorder = ViewState["SortOrder"].ToString();

                if (sortorder == "ASC")
                {
                    img1.ImageUrl = "./images/up.png";
                    img1.AlternateText = "Ascending";                    

                    img2.ImageUrl = "./images/up.png";
                    img2.AlternateText = "Ascending";

                    img3.ImageUrl = "./images/up.png";
                    img3.AlternateText = "Ascending";
                }
                else
                {
                    img1.ImageUrl = "./images/down.png";
                    img1.AlternateText = "Descending";

                    img2.ImageUrl = "./images/down.png";
                    img2.AlternateText = "Descending";

                    img3.ImageUrl = "./images/down.png";
                    img3.AlternateText = "Descending";
                }
            }
            else
            {
                img1.ImageUrl = "./images/down.png";
                img1.AlternateText = "Descending";

                img2.ImageUrl = "./images/down.png";
                img2.AlternateText = "Descending";

                img3.ImageUrl = "./images/down.png";
                img3.AlternateText = "Descending";
            }
        }
    }
}